#include <iostream>

#include "OsxSlave.h"

OsxSlave::OsxSlave(std::string remote_ip, int port, MncPoint screen_size)
    :Slave(remote_ip, port, screen_size)
{
}

OsxSlave::~OsxSlave()
{
}

void OsxSlave::EnactMouseEvent(abyte event_type, MncPoint point, abyte coordinate_type)
{
    CGEventType osx_event_type = MncEventTypeToOsxEventType(event_type);
    short x = 0, y = 0;
    
    if(coordinate_type != Message::kCoordinateRelative)
    {
        printf("Received a message without relative coordinates !!\n");
        return;
    }
    
    if(coordinate_type == Message::kCoordinateRelative)
    {
        MncPoint current_location = GetMouseLocation();
        x = current_location.x + point.x;
        y = current_location.y + point.y;
    }
    
    printf("posting event %c: %hd, %hd (%c)\n", osx_event_type, x, y, coordinate_type);
    //EnactMouseEvent(osx_event_type, CGPointMake(x, y), coordinate_type);
}

void OsxSlave::EnactMouseEvent(CGEventType type, CGPoint point, abyte coordinate_type)
{
    CGEventRef event = CGEventCreateMouseEvent(NULL, type, point, 0);
    CGEventPost(kCGHIDEventTap, event);
    CFRelease(event);
}

MncPoint Slave::GetMouseLocation()
{
    CGEventRef dummy_event = CGEventCreate(NULL);
    CGPoint osx_point = CGEventGetLocation(dummy_event);
    return MncPoint(osx_point.x, osx_point.y);
}

CGEventType OsxSlave::MncEventTypeToOsxEventType(abyte mnc_event_type)
{
    switch (mnc_event_type)
    {
        case Message::kEventMouseMove:
            return kCGEventMouseMoved;
            
        default:
            return NULL;
    }
}